package utils 
{
	import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.BlendMode;
    import flash.display.Sprite;
    import flash.events.Event;
    //import flash.events.MouseEvent;
    import flash.filters.BlurFilter;
    import flash.filters.GlowFilter;
    import flash.geom.Matrix;
    import flash.geom.Point;
	import flash.display.DisplayObject;
	/**
	 * ...
	 * @author FireKnight
	 */
	public class Cover extends Sprite
	{
		private var parentMovie:DisplayObject;
		private var coverSquare:Sprite;
		private var blurredParent:Bitmap;
		
		private var stageW:Number; 
		private var stageH:Number;
		public function Cover(parent:DisplayObject,w:Number = 500, h:Number = 400) 
		{
			parentMovie = parent;
			stageW = w;
			stageH = h;
			super();
			
			coverSquare = new Sprite();
			coverSquare.graphics.beginFill(0xffffff,0.05);
			coverSquare.graphics.drawRect(0,0,parentMovie.stage.stageWidth,parentMovie.stage.stageHeight);
			coverSquare.graphics.endFill();
			addChild(coverSquare);
			
			blurredParent = new Bitmap();
			this.addChild(blurredParent);
			//trace("blurredParent="+blurredParent);
			this.addEventListener(Event.ENTER_FRAME,initCover);
			showCover();
		}
		
		
			
			

			
		public function hideCover():void
		{
			//if(e.stageX < stageW && e.stageX > 0 && e.stageY < stageH && e.stageY > 0){
				this.visible = false;
			//}
            //this.dispatchEvent( new Event(Event.DEACTIVATE) );
		}
		private function showCover(e:Event = null):void
		{
			if(!this.visible){
				refresh();
			}
			// Turn on cover
			this.visible = true;
            //this.dispatchEvent( new Event(Event.ACTIVATE) );
		}
		private function initCover(e:Event):void
		{
			this.removeEventListener(Event.ENTER_FRAME,initCover);
			refresh();
			// Turn on cover
			this.visible = true;			
		}
		public function refresh():void
		{
			var bits:BitmapData = new BitmapData(stageW,stageH,false,0);
			bits.draw(coverSquare);
			bits.draw(parentMovie);
			var backgroundImage:Bitmap = new Bitmap(bits,"auto",true);
			backgroundImage.filters = new Array( new BlurFilter(6,6,4) );

			// Copy the blurred text and add the text
			var textOverlay:BitmapData = new BitmapData(stageW,stageW,false,0);
			textOverlay.draw(bits);
			textOverlay.draw(backgroundImage,null, null, BlendMode.LIGHTEN);
			
            textOverlay.applyFilter(textOverlay, textOverlay.rect, new Point(), new BlurFilter(5,5));
            textOverlay.draw(textOverlay);
			blurredParent.bitmapData = textOverlay;
			
		}
		
		public function gc():void
		{
			if(blurredParent)
			{
				blurredParent.bitmapData.dispose();
			}
		}
		
		
	}

}